package com.hs.controller;

import com.google.code.kaptcha.Constants;
import com.hs.entity.TbUser;

import com.hs.service.UserService;
import com.hs.shiro.UserRealm;
import com.hs.utils.MD5Utils;
import com.hs.utils.MailUtils;
import com.hs.utils.ResultUtils;
import com.hs.utils.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;

@Controller
public class LoginController {

    @Autowired
    private UserRealm userRealm;

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/login/do")
    @ResponseBody
    public String doLogin(String account, String password, String captcha, Boolean rememberMe, HttpSession session)
    {
        /*获取正确的验证码*/
        String realCaptcha= (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        /*判断验证码是否一致*/
        if(!realCaptcha.equals(captcha)){
            return "kaptcha";
        }
        /*用户认证，获取登录主体*/
        Subject subject= SecurityUtils.getSubject();
        /*创建token*/
        UsernamePasswordToken token=new UsernamePasswordToken(account,password,rememberMe);
        try {
            subject.login(token);
            /*调用subject.login(token) 接下来到支持处理这个token的realm中调用 realm
             doGetAuthenticationInfo 鉴权，鉴权后，session中就存有你的登录信息了*/
            /*鉴权成功*/
            if(subject.isAuthenticated()){
                /*返回ok*/
                return "ok";
            }else {
                /*鉴权失败
                * 返回error*/
                return "error";
            }
        }catch (Exception e){
            return "error";
        }
    }

    /*返回到index页面*/
    @RequestMapping("/index")
    public String index(HttpSession session){
        TbUser user=ShiroUtils.getSessionUser();
        session.setAttribute("user",user);
        return "index";
    }

    /*忘记密码的处理方法
    * 必须现在shiro里面声明一下，否则无法访问*/
    @RequestMapping("/forget/do")
    private void forgetdo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*从前台获取用户填写的数据*/
        String account= request.getParameter("account");
        /*账号*/
        String realname= request.getParameter("realname");
        /*姓名*/
        String email=request.getParameter("email");
        /*邮箱*/
        String roleid=request.getParameter("roleid");
        /*角色ID*/
        String gender=request.getParameter("gender");
        /*性别*/
        response.setCharacterEncoding("UTF-8");
        /*防止前台乱码*/
        TbUser forget=userService.queryForForgetPassword(account,realname,email,roleid, Integer.valueOf(gender));
        /*身份验证，查询用户是否存在*/
        if (forget!=null){
            Integer forgetId = forget.getId();
            /*返回前台数据*/
            ResultUtils.success(response,forgetId,"验证成功");
        }else{
            ResultUtils.error(response,102,"验证信息有误，请检查");
        }
    }

    /*分步表单的第二步处理
    * */
    @RequestMapping("/forget/execute")
    private void forgetPasswordChange(HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*获取邮箱*/
        String email=request.getParameter("email");
        /*获取角色的id*/
        String id = request.getParameter("id");
        /*防止页面乱码*/
        response.setCharacterEncoding("UTF-8");
        try {
            /*通过邮箱，发送密码*/
            Integer password= MailUtils.sendPassword(email);
            /*修改用户密码*/
            Integer rows=userService.changeForForgetPassword(MD5Utils.getMD5(String.valueOf(password)), Integer.valueOf(id));
            /*row为1说明，受影响的行数为1*/
            if(rows==1){
                ResultUtils.success(response,"新密码已成功生成，请前往邮件查看");
            }else {
                ResultUtils.error(response,43,"密码修改失败");
            }
            /*异常处理*/
        }catch (SQLException e){
            e.printStackTrace();
            ResultUtils.error(response,41,"数据库异常，请联系管理员");
        }catch (NumberFormatException e){
            e.printStackTrace();
            ResultUtils.error(response,41,"参数异常，请联系管理员");
        }
        catch (Exception e) {
            e.printStackTrace();
            ResultUtils.error(response,40,"邮件发送失败,请检查邮箱格式");
        }
    }

    @RequestMapping("/logout")
    @ResponseBody
    protected String logout(){
        try{
            Subject subject= SecurityUtils.getSubject();
            Session shiroSession= subject.getSession();
            shiroSession.removeAttribute("user");
            return "ok";
        }catch (Exception e)
        {
            return "error";
        }
    }

    @RequestMapping("/forget")
    private String forget(){
        return "forget";
    }
}
